#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
增强版流程编排器

Workflow 提供增强功能层：
- 备份和还原
- 事务管理
- 性能监控
- 验证和报告

核心混淆逻辑由 Obfuscator 负责执行。

架构：
    Workflow (增强层)
        ↓
    Obfuscator (核心混淆)
        ↓
    Features (功能模块)
        ├── DeadCodeInjector
        ├── DummyCodeGenerator
        ├── CodeInjector
        └── ImageObfuscator
"""

import os
import time
import json
from typing import Dict, Any, Optional
from dataclasses import dataclass
from pathlib import Path

from ..utils_module.logger import ObfuscationLogger
from ..obfuscation_module.obfuscator import Obfuscator, ObfuscationLevel
from ..utils_module.backup_manager import ProjectBackupManager
from ..processing_module.transaction_manager import TransactionManager


@dataclass
class WorkflowConfig:
    """工作流配置"""
    use_cache: bool = True
    enable_parallel: bool = True
    max_workers: int = 8
    batch_size: int = 50
    enable_transactions: bool = True
    enable_incremental: bool = False
    obfuscation_level: ObfuscationLevel = ObfuscationLevel.ADVANCED
    auto_optimize: bool = True


class EnhancedWorkflowOrchestrator:
    """流程编排器"""

    def __init__(self, obfuscator: Obfuscator, logger: ObfuscationLogger,
                 workflow_config: WorkflowConfig = None):
        """
        初始化流程编排器

        Args:
            obfuscator: 混淆器实例
            logger: 日志记录器
            workflow_config: 工作流配置
        """
        self.obfuscator = obfuscator
        self.logger = logger
        self.config = obfuscator.config
        self.workflow_config = workflow_config or WorkflowConfig()

        # 初始化优化组件
        self._init_components()

        # 工作流状态
        self.workflow_id = f"workflow_{int(time.time())}"
        self.start_time = None
        self.stats = {}

        # 备份管理器
        self.backup_manager = ProjectBackupManager(obfuscator.config, logger)

    def _init_components(self):
        """初始化当前架构所需的核心组件"""
        self.transaction_manager: Optional[TransactionManager] = None

        if self.workflow_config.enable_transactions:
            tx_workspace = os.path.join(self.config.output_dir, '.tx_workspace')
            self.transaction_manager = TransactionManager(self.logger, tx_workspace)
            self.logger.log_operation("事务管理", f"事务工作区初始化: {tx_workspace}")
        else:
            self.logger.log_operation("事务管理", "已禁用事务管理")

    def obfuscate_project(self) -> Dict[str, Any]:
        """
        执行增强版混淆流程

        使用 Obfuscator 执行核心混淆逻辑，Workflow 提供额外的增强功能：
        - 备份和还原
        - 事务管理
        - 验证和报告
        - 性能监控

        Returns:
            处理结果统计
        """
        self.start_time = time.time()
        self.logger.log_operation("开始增强混淆流程", f"项目: {self.config.project_path}")

        backup_path = None
        tx_id = None

        try:
            # Phase 1: 准备阶段（备份、环境检查）
            backup_path = self._prepare_phase()

            # Phase 2: 开启事务（如果启用）
            if self.transaction_manager:
                tx_id = self.transaction_manager.begin_transaction()
                self.logger.log_operation("事务管理", f"事务ID: {tx_id}")

            # Phase 3: 执行混淆（使用 Obfuscator）
            level = self.workflow_config.obfuscation_level
            if isinstance(level, str):
                try:
                    level = ObfuscationLevel(level)
                except ValueError:
                    level = ObfuscationLevel.ADVANCED

            self.logger.log_operation("Phase 3", "执行混淆（调用 Obfuscator）")
            obfuscation_result = self.obfuscator.obfuscate(
                project_path=self.config.project_path,
                level=level,
                options={
                    'use_cache': self.workflow_config.use_cache,
                    'incremental': self.workflow_config.enable_incremental,
                    'dry_run': self.config.dry_run
                }
            )

            # Phase 4: 验证阶段
            validation_result = self._validation_phase()

            # Phase 5: 提交事务
            if tx_id:
                self.transaction_manager.commit(tx_id)
                self.logger.log_operation("事务管理", "事务已提交")

            # Phase 6: 完成阶段
            self._completion_phase()

            # 收集统计信息
            self.stats = self._collect_statistics_from_result(
                obfuscation_result,
                validation_result
            )

            self.logger.log_operation(
                "混淆流程完成",
                f"总耗时: {time.time() - self.start_time:.2f}秒"
            )

            return self.stats

        except Exception as e:
            self.logger.log_error(f"混淆流程失败: {e}")

            # 回滚事务
            if tx_id:
                self.transaction_manager.rollback(tx_id)
                self.logger.log_operation("事务管理", "事务已回滚")

            # 恢复备份
            if backup_path:
                self.logger.log_operation("备份还原", "开始还原项目")
                self.backup_manager.restore_from_backup(
                    backup_path,
                    self.config.project_path
                )

            raise

    def _prepare_phase(self) -> str:
        """
        准备阶段

        Returns:
            备份路径
        """
        self.logger.log_operation("Phase 1", "准备阶段")

        # 创建备份
        backup_path = self.backup_manager.create_full_backup(
            self.config.project_path,
            f"enhanced_backup_{self.workflow_id}"
        )

        # 环境检查
        self._check_environment()

        return backup_path


    def _validation_phase(self) -> Dict[str, Any]:
        """
        验证阶段

        Returns:
            验证结果
        """
        self.logger.log_operation("Phase 5", "验证阶段")

        validation_result = {
            'syntax_valid': True,
            'build_valid': False,
            'ide_valid': False
        }

        try:
            # IDE/编译器验证
            if hasattr(self.obfuscator, 'perform_ide_validation'):
                validation_result['ide_valid'] = self.obfuscator.perform_ide_validation()

            # 构建验证（如果配置了）
            if hasattr(self.obfuscator, 'perform_build_validation'):
                validation_result['build_valid'] = self.obfuscator.perform_build_validation()

        except Exception as e:
            self.logger.log_warning(f"验证失败: {e}")

        return validation_result

    def _completion_phase(self):
        """完成阶段"""
        self.logger.log_operation("Phase 6", "完成阶段")

        # 生成报告
        self._generate_enhanced_report()

        # 清理临时文件
        self._cleanup_temp_files()

        # 创建检查点
        if self.transaction_manager:
            self.transaction_manager.create_checkpoint()

    def _collect_statistics_from_result(self, obfuscation_result,
                                        validation_result: Dict[str, Any]) -> Dict[str, Any]:
        """
        从 Obfuscator 结果收集统计信息

        Args:
            obfuscation_result: Obfuscator 的混淆结果
            validation_result: 验证结果

        Returns:
            统计信息
        """
        processed_files = max(obfuscation_result.files_processed, 0)
        elapsed_time = max(time.time() - self.start_time, 0.0)

        stats = {
            'workflow_id': self.workflow_id,
            'total_time': elapsed_time,
            'files_processed': obfuscation_result.files_processed,
            'symbols_obfuscated': obfuscation_result.symbols_obfuscated,
            'cache_hits': obfuscation_result.metadata.get('cache_hits', 0),
            'parallel_workers': self.workflow_config.max_workers if self.workflow_config.enable_parallel else 1,
            'validation': validation_result,
            'obfuscation_success': obfuscation_result.success,
            'obfuscation_time': obfuscation_result.processing_time,
            'errors': obfuscation_result.errors,
            'performance': {
                'files_per_second': (obfuscation_result.files_processed / elapsed_time) if elapsed_time > 0 else 0,
                'symbols_per_second': (obfuscation_result.symbols_obfuscated / elapsed_time) if elapsed_time > 0 else 0,
                'workflow_overhead': max(0.0, elapsed_time - obfuscation_result.processing_time),
                'avg_file_time': (elapsed_time / processed_files) if processed_files else 0,
                'throughput': (obfuscation_result.files_processed / elapsed_time) if elapsed_time > 0 else 0
            }
        }

        return stats

    def _generate_enhanced_report(self):
        """生成增强版报告"""
        report_path = os.path.join(
            self.config.output_dir,
            f"enhanced_report_{self.workflow_id}.json"
        )

        with open(report_path, 'w', encoding='utf-8') as f:
            json.dump(self.stats, f, indent=2, ensure_ascii=False)

        self.logger.log_operation("报告生成", f"报告已保存到 {report_path}")

    def _cleanup_temp_files(self):
        """清理临时文件"""
        # 清理备份文件
        for file_path in Path(self.config.project_path).rglob('*.bak'):
            try:
                os.remove(file_path)
            except OSError as e:
                self.logger.log_warning(f"无法删除临时文件 {file_path}: {e}")

    def _check_environment(self):
        """检查环境"""
        # 检查项目路径
        if not os.path.exists(self.config.project_path):
            raise FileNotFoundError(f"项目路径不存在: {self.config.project_path}")

        # 创建必要目录
        required_dirs = [
            self.config.backup_dir,
            self.config.log_dir,
            self.config.output_dir
        ]
        for dir_path in required_dirs:
            os.makedirs(dir_path, exist_ok=True)

    def get_performance_report(self) -> str:
        """
        获取性能报告

        Returns:
            性能报告文本
        """
        if not self.stats:
            return "尚未执行混淆流程"

        report = []
        report.append("=" * 60)
        report.append("增强版混淆流程性能报告")
        report.append("=" * 60)
        report.append(f"工作流ID: {self.stats['workflow_id']}")
        report.append(f"总耗时: {self.stats['total_time']:.2f}秒")
        report.append(f"处理文件数: {self.stats['files_processed']}")
        report.append(f"混淆符号数: {self.stats['symbols_obfuscated']}")
        report.append(f"缓存命中数: {self.stats['cache_hits']}")
        report.append(f"并行工作线程: {self.stats['parallel_workers']}")
        report.append("\n性能指标:")
        report.append(f"  文件处理速度: {self.stats['performance']['files_per_second']:.2f} 文件/秒")
        report.append(f"  平均文件耗时: {self.stats['performance']['avg_file_time']:.3f}秒")
        report.append(f"  吞吐量: {self.stats['performance']['throughput']:.2f} 任务/秒")
        report.append("\n验证结果:")
        for key, value in self.stats['validation'].items():
            report.append(f"  {key}: {value}")
        report.append("=" * 60)

        return "\n".join(report)
